#!/usr/bin/env python
import sys
import antlr3
from parsing.GencfaLexer import GencfaLexer
from parsing.GencfaParser import GencfaParser

class GenInput:
    
    def __init__(self, stream):
        """
        Receives input file from main module and passes the stream on to antlr
        """
        self.symbol_table = {}
        self.background = []
        self.startshape = ''
        self.parser = None
        
        self.cStream = antlr3.StringStream(stream.read())
        self.lexer = GencfaLexer(self.cStream)
        self.tStream = antlr3.CommonTokenStream(self.lexer)
        self.parser = GencfaParser(self.tStream)
        self.parser.cfdg() #Execs first parser grammar rule
    
    def __str__(self):
        return str(self.symbol_table)
    
    def parse(self):
        self.symbol_table = {}
        "Sets a symbol table up with rule names and invocations."
        self.startshape = self.parser.sshape #gets startshape
        self.background = self.parser.bground #gets background params    
        self.names = self.parser.names #gets symbols list from GencfaParser.py
        
        count = 0
        cur_rule = ""
        for rule in self.names:
            if cur_rule == rule[-1]:
                count = count + 1               
            else:                 
                count = 1
                cur_rule = rule[-1]
            instance_name = rule[-1].upper() + "#" + str(count) #instance name e.g. QUAD#3
            
            params = []
            for invoc in rule[:-1]:     #rule name is last on list. The rest are invocations.
                building = []
                for value in invoc[:-1]:
                    building.append(tuple(value.split()))
                building.append(invoc[-1].upper())
                params.append(building)
            
            self.symbol_table[instance_name] = params 
            print("SYMBOL: " + instance_name + " CONTAINS: " + str(self.symbol_table[instance_name]))

    def is_number(self, s):
        try:
            float(s)
            return True
        except ValueError:
            return False   
    
